<template>
  <div class="active">
    <h2>供应商评审总分与排名</h2>
    <el-table :data="supplierReviews" stripe style="width: 100%" class="end">
      <el-table-column
        prop="key"
        label="序号"
        width="81"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierName"
        label="报名供应商"
        width="207"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="priceScore"
        label="价格分"
        width="80"
        align="center"
        :formatter="formatScore"
      ></el-table-column>

      <el-table-column
        prop="businessScore"
        label="商务分"
        width="80"
        align="center"
        :formatter="formatScore"
      ></el-table-column>
      <el-table-column label="技术分" align="center">
        <template
          v-for="(item, index) in supplierReviews[0]?.technicalScores || []"
          :key="index"
        >
          <el-table-column
            :prop="`technicalScores[${index}]`"
            :label="getname(index)"
            align="center"
          >
            <template #default="scope">
              <div>{{ scope.row.technicalScores[index] }}</div>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          prop="averageTechnicalScore"
          label="平均分"
          width="70"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="totalScore"
        label="综合得分"
        width="100"
        align="center"
        fixed="right"
      ></el-table-column>
      <el-table-column
        prop="rank"
        label="排名"
        width="70"
        align="center"
        fixed="right"
      ></el-table-column>
    </el-table>
    <h3>项目评审结果</h3>
    <!-- 项目评审结果 -->
    <el-table
      :data="projectReviews"
      stripe
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        prop="key"
        label="序号"
        width="81"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="applyTime"
        label="报名时间"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="报名供应商"
        width="300"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="资质审查"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="score"
        label="综合得分"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="reviewResult"
        label="评审结果"
        width="100"
        align="center"
      ></el-table-column>
    </el-table>
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <h3>中选供应商结果确认</h3>
      <el-button type="primary" @click="getInfo(true)">刷新</el-button>
    </div>
    <el-form :model="SelectedForm" label-width="250px">
      <div v-if="OverStatus == 'continue'">
        <el-form-item label="第一候选人：">
          <el-select
            @change="editForm('outbidOneId')"
            v-model="SelectedForm.outbidOneId"
            placeholder="请选择第一候选人"
            style="width: 500px"
          >
            <el-option
              v-for="candidate in candidates"
              :key="candidate.id"
              :label="candidate.name"
              :value="candidate.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目中止理由：" v-if="OverType">
          <el-input
            placeholder="请输入项目中止理由"
            style="width: 500px"
            type="textarea"
            v-model="SelectedForm.breakRemark"
            @blur="editform"
          ></el-input>
        </el-form-item>
        <el-form-item label="中选理由：" v-if="!OverType">
          <el-input
            @blur="editform"
            placeholder="请输入第一候选人中选理由"
            type="textarea"
            style="width: 500px"
            v-model="SelectedForm.remarkOne"
          ></el-input>
        </el-form-item>
        <el-form-item label="第二候选人：" v-if="!OverType">
          <el-select
            @change="editForm('outbidTwoId')"
            v-model="SelectedForm.outbidTwoId"
            placeholder="请选择第二候选人"
            style="width: 500px"
          >
            <el-option
              v-for="candidate in candidates"
              :key="candidate.id"
              :label="candidate.name"
              :value="candidate.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中选理由：" v-if="!OverType">
          <el-input
            @blur="editform"
            placeholder="请输入第二候选人中选理由"
            type="textarea"
            style="width: 500px"
            v-model="SelectedForm.remarkTwo"
          ></el-input>
        </el-form-item>
        <el-form-item label="第三候选人：" v-if="!OverType">
          <el-select
            @change="editForm('outbidThreeId')"
            v-model="SelectedForm.outbidThreeId"
            placeholder="请选择第三候选人"
            style="width: 500px"
          >
            <el-option
              v-for="candidate in candidates"
              :key="candidate.id"
              :label="candidate.name"
              :value="candidate.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中选理由：" v-if="!OverType">
          <el-input
            @blur="editform"
            placeholder="请输入第三候选人中选理由"
            type="textarea"
            style="width: 500px"
            v-model="SelectedForm.remarkThree"
          ></el-input>
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item label="强制终止评审理由：">
          <el-input
            placeholder="请输入强制终止评审理由"
            style="width: 500px"
            type="textarea"
            v-model="SelectedForm.breakRemark"
            @blur="editform"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item :label="`主持人(${hostname})签名确认结果时间：`">
        <el-input
          style="width: 500px"
          v-model="SelectedForm.restartCheck.restartCheckTime"
          placeholder="请主持人签名"
          disabled
        ></el-input>
        <span class="link" @click="StartSingin">主持评审结果确认签名</span>
      </el-form-item>
      <el-form-item :label="`主持人(${hostname})评审结果确认签名：`">
        <div class="tablet">
          <el-image
            v-if="SelectedForm.restartCheck.restartCheck"
            :src="baseURL + SelectedForm.restartCheck.restartCheck"
          >
            <template #error>
              <div class="image-slot"></div>
            </template>
          </el-image>
        </div>
      </el-form-item>

      <el-form-item
        :label="`评委${index + 1}(${item.name})评审结果确认签名：`"
        v-for="(item, index) in SelectedForm.Signlist"
        :key="index"
      >
        <div class="tablet">
          <el-image v-if="item.restartCheck" :src="baseURL + item.restartCheck">
            <template #error>
              <div class="image-slot"></div>
            </template>
          </el-image>
        </div>
      </el-form-item>
      <el-form-item :label="`监督人(${supervisename})评审结果确认签名：`">
        <div class="tablet">
          <el-image
            v-if="SelectedForm.supervisorSignature.restartCheck"
            :src="baseURL + SelectedForm.supervisorSignature.restartCheck"
          >
            <template #error>
              <div class="image-slot"></div>
            </template>
          </el-image>
        </div>
      </el-form-item>

      <sxb ref="Tablet" @Return="Return" style="display: none" />
      <div
        class="endbutton"
        v-if="Previous == 'taskResultBreak' || Previous == 'taskBreak'"
      >
        <el-button @click="prevPage">上一步</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
      <div class="endbutton" v-else>
        <el-button @click="prevPage">上一步</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="danger" @click="terminate">强制中止</el-button>
      </div>
    </el-form>
    <el-dialog
      v-model="promptDiv"
      title="强制终止评审"
      width="500"
      align-center
    >
      <div style="margin-bottom: 20px; text-align: center">
        注意！本操作将导致本项目评审直接变成项目终止结果（操作不可逆），请确认是否要终止评审？
      </div>
      <span style="width: 100%; display: flex; justify-content: center">
        <el-button type="primary" @click="promptDiv = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { judgeProjectInfo } from "@/api/project.js";
import { getDictList, getDict, nowTime, getdict } from "@/utils/common.js";
import {
  totalScore,
  projectInfoAndSupplierAndJudge,
  choiceSupplier,
  startJudgeSign,
  auditsign,
  queryTaskId,
  execTask,
  selectResultStatus,
} from "@/api/examine.js";
import { ElMessage } from "element-plus";

const emit = defineEmits(["next-step"]);
import sxb from "@/components/sxb.vue";
const route = useRoute();
const id = computed(() => route.query.id);
const judgeId = ref("");
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
});
const userInfo = computed(() => JSON.parse(localStorage.getItem("judgeInfo")));
const Tablet = ref(null);
// 定义数据
const SelectedForm = ref({
  outbidOneId: "",
  remarkOne: "",
  outbidTwoId: "",
  remarkTwo: "",
  outbidThreeId: "",
  remarkThree: "",
  restartCheckTime: "",
  restartCheck: "",
  Signlist: [],
  supervisorSignature: "",
});
const hostname = ref("");
const supervisename = ref("");
const baseURL = import.meta.env.VITE_APP_BASE_API;
const supplierReviews = ref([]);
const projectReviews = ref([]);
const OverStatus = ref("");
const OverType = ref(false);
const candidates = ref([]);
const projectInfo = ref({});
const judgeList = ref([]);
const editForm = (key) => {
  const { outbidOneId, outbidTwoId, outbidThreeId } = SelectedForm.value;

  // 检查是否有相同的值
  // 如果有相同的值，清空 SelectedForm.value 中对应的字段
  if (
    key === "outbidOneId" &&
    (outbidOneId === outbidTwoId || outbidOneId === outbidThreeId) &&
    outbidOneId != null
  ) {
    SelectedForm.value.outbidOneId = "";
    ElMessage({
      message: "候选人禁止重复！",
      type: "error",
    });
    return;
  }
  if (
    key === "outbidTwoId" &&
    (outbidTwoId === outbidOneId || outbidTwoId === outbidThreeId) &&
    outbidTwoId != null
  ) {
    SelectedForm.value.outbidTwoId = "";
    ElMessage({
      message: "候选人禁止重复！",
      type: "error",
    });
    return;
  }
  if (
    key === "outbidThreeId" &&
    (outbidThreeId === outbidOneId || outbidThreeId === outbidTwoId) &&
    outbidThreeId != null
  ) {
    SelectedForm.value.outbidThreeId = "";
    ElMessage({
      message: "候选人禁止重复！",
      type: "error",
    });
    return;
  }
  editform();
};
const editform = () => {
  const params = {
    id: id.value,
    oaCode: projectInfo.value.oaCode,
    outbidOneId: SelectedForm.value.outbidOneId,
    outbidTwoId: SelectedForm.value.outbidTwoId,
    outbidThreeId: SelectedForm.value.outbidThreeId,
    remarkOne: SelectedForm.value.remarkOne,
    remarkTwo: SelectedForm.value.remarkTwo,
    remarkThree: SelectedForm.value.remarkThree,
    breakRemark: SelectedForm.value.breakRemark,
  };
  console.log(params);

  choiceSupplier(params).then((res) => {
    if (res.code == "200") {
    }
  });
};
const submit = () => {
  const param = { projectId: id.value, execStatus: "continue" };
  execTask(param).then((res) => {
    if (res.code) {
      window.location.reload();
    }
  });
};
const promptDiv = ref(false);
const terminate = () => {
  const param = { projectId: id.value, execStatus: "break" };
  execTask(param).then((res) => {
    if (res.code) {
      window.location.reload();
    }
  });
};
const getInfo = (boolean) => {
  SelectedForm.value = {
    outbidOneId: "",
    remarkOne: "",
    outbidTwoId: "",
    remarkTwo: "",
    outbidThreeId: "",
    remarkThree: "",
    restartCheckTime: "",
    restartCheck: "",
    Signlist: [],
    supervisorSignature: "",
  };
  totalScore({ projectId: id.value }).then((res) => {
    if (res.code == "200") {
      supplierReviews.value = [];
      for (let i = 0; i < res.data.length; i++) {
        let averageTechnicalScore = null; // 技术平均分
        let priceScore = null;
        let businessScore = null;
        const scoreMap = {}; // 用于跟踪技术分的累积

        for (let j = 0; j < res.data[i].scoreList.length; j++) {
          const scoreItem = res.data[i].scoreList[j];

          // 根据 type 添加到相应的属性中或进行累加
          if (scoreItem.type === "score_skill") {
            if (!scoreMap[scoreItem.markId]) {
              scoreMap[scoreItem.markId] = scoreItem.score;
            } else {
              // 如果已经存在相同的 markId，则累加分数
              scoreMap[scoreItem.markId] += scoreItem.score;
            }
          } else if (scoreItem.type === "score_average") {
            // 查找平均分
            averageTechnicalScore =
              scoreItem.score >= 0 ? scoreItem.score : "分数异常";
          } else if (scoreItem.type === "score_price") {
            // 查找价格分
            priceScore = scoreItem.score >= 0 ? scoreItem.score : "分数异常";
          } else if (scoreItem.type === "score_business") {
            // 查找商务分
            businessScore = scoreItem.score >= 0 ? scoreItem.score : "分数异常";
          }
        }

        // 构建 supplierReviews.value 数组
        supplierReviews.value.push({
          key: i + 1,
          supplierCode: res.data[i].supplierCode,
          supplierName: res.data[i].supplierName,
          priceScore: priceScore,
          businessScore: businessScore,
          technicalScores: scoreMap,
          averageTechnicalScore: averageTechnicalScore,
          totalScore: res.data[i].totalScore,
          rank: i + 1,
        });
      }
    }
  });
  try {
    projectInfoAndSupplierAndJudge({ id: id.value }).then((res) => {
      if (res.code == "200") {
        candidates.value = [];
        judgeList.value = res.data.judgeList;
        projectReviews.value = [];
        SelectedForm.value.outbidOneId = res.data.outbidOneId;
        if (supplierReviews.value.length <= 0) {
          const scoreMap = {}; // 用于跟踪技术分的累积
          for (let i = 0; i < res.data.judgeList.length; i++) {
            if (res.data.judgeList[i].type == "judge_jury") {
              scoreMap[res.data.judgeList[i].userId] = "/";
            }
          }
          for (let i = 0; i < res.data.supplierList.length; i++) {
            supplierReviews.value.push({
              key: i + 1,
              supplierCode: res.data.supplierList[i].supplierCode,
              supplierName: res.data.supplierList[i].supplierName,
              priceScore: "/", // 初始化为 null
              businessScore: "/", // 初始化为 null
              technicalScores: scoreMap,
              averageTechnicalScore: "/",
              totalScore: "/",
              rank: "/",
            });
          }
        } else {
          SelectedForm.value.outbidTwoId = res.data.outbidTwoId;
          SelectedForm.value.outbidThreeId = res.data.outbidThreeId;
          SelectedForm.value.remarkOne = res.data.remarkOne;
          SelectedForm.value.remarkTwo = res.data.remarkTwo;
          SelectedForm.value.remarkThree = res.data.remarkThree;
        }
        if (res.data.breakRemark) {
          SelectedForm.value.breakRemark = res.data.breakRemark;
        }

        for (let i = 0; i < res.data.judgeList.length; i++) {
          switch (res.data.judgeList[i].type) {
            case "judge_jury":
              SelectedForm.value.Signlist.push({
                id: res.data.judgeList[i].id,
                restartCheck: res.data.judgeList[i].endCheck,
                name: res.data.judgeList[i].name,
              });
              break;
            case "judge_custodian":
              supervisename.value = res.data.judgeList[i].name;
              SelectedForm.value.supervisorSignature = {
                id: res.data.judgeList[i].id,
                restartCheck: res.data.judgeList[i].endCheck,
              };
              break;
            case "judge_compere":
              judgeId.value = res.data.judgeList[i].id;
              hostname.value = res.data.judgeList[i].name;
              SelectedForm.value.restartCheck = {
                id: res.data.judgeList[i].id,
                restartCheck: res.data.judgeList[i].endCheck,
                restartCheckTime: res.data.judgeList[i].endCheckTime,
              };
              break;
          }
        }
        candidates.value.push({
          id: "0",
          name: "无",
        });
        // 首先根据价格对供应商列表进行排序，并复制到新的数组中
        let sortedSuppliers = res.data.supplierList
          // 首先过滤掉没有 price 属性的供应商
          .filter(
            (supplier) =>
              supplier.price !== undefined && supplier.price !== null
          )
          // 然后根据 price 属性进行升序排序
          .sort((a, b) => a.price - b.price);

        // 获取最低价格
        let lowestPrice =
          sortedSuppliers.length > 0 ? sortedSuppliers[0].price : Infinity;

        // 定义最高可接受价格为最低价格的120%
        let maxAcceptablePrice = lowestPrice * 1.2;
        for (let i = 0; i < res.data.supplierList.length; i++) {
          if (res.data.supplierList[i].status != "apply_supplier_no_pass") {
            if (res.data.priceEquation == "equation_floor_price") {
              let currentSupplierInSorted = sortedSuppliers.find(
                (supplier) =>
                  supplier.supplierId === res.data.supplierList[i].supplierId
              );
              // 查找当前供应商在排序后的数组中的位置

              // 如果找到了供应商并且其价格在可接受范围内，则添加到 candidates.value
              if (
                currentSupplierInSorted &&
                currentSupplierInSorted.price < maxAcceptablePrice
              ) {
                candidates.value.push({
                  id: res.data.supplierList[i].supplierId,
                  name: res.data.supplierList[i].name,
                });
              }
            } else if (res.data.priceEquation == "equation_float_prob") {
              if (res.data.supplierList[i].price < 20) {
                candidates.value.push({
                  id: res.data.supplierList[i].supplierId,
                  name: res.data.supplierList[i].name,
                });
              }
            } else {
              candidates.value.push({
                id: res.data.supplierList[i].supplierId,
                name: res.data.supplierList[i].name,
              });
            }
          }
          const formattedDateTime = res.data.supplierList[i].applyTime.slice(
            0,
            16
          );
          let reviewResult = "";
          if (res.data.outbidOneId == res.data.supplierList[i].supplierId) {
            reviewResult = "第一候选人";
          } else if (
            res.data.outbidTwoId == res.data.supplierList[i].supplierId
          ) {
            reviewResult = "第二候选人";
          } else if (
            res.data.outbidThreeId == res.data.supplierList[i].supplierId
          ) {
            reviewResult = "第三候选人";
          } else if (
            res.data.outbidOneId ||
            res.data.outbidTwoId ||
            res.data.outbidThreeId
          ) {
            reviewResult = "落选";
          } else {
            reviewResult = "待定";
          }
          projectReviews.value.push({
            key: i + 1,
            applyTime: formattedDateTime,
            supplierCode: res.data.supplierList[i].supplierCode,
            name: res.data.supplierList[i].name,
            status:
              res.data.supplierList[i].status == "apply_supplier_pass"
                ? "符合"
                : "异常",
            score: res.data.supplierList[i].score,
            reviewResult: reviewResult,
          });
        }
        if (boolean) {
          ElMessage({
            message: "刷新成功",
            type: "success",
          });
        }
      }
    });
  } catch (error) {}
  selectResultStatus({ projectId: id.value }).then((res) => {
    if (res.code == "200") {
      OverStatus.value = res.data;
      OverType.value =
        (SelectedForm.value.breakRemark ||
          Previous.value == "taskBreak" ||
          Previous.value == "taskExamine") &&
        OverStatus.value != "continue";
    }
  });
};
const getname = (key) => {
  for (let i = 0; i < judgeList.value.length; i++) {
    if (judgeList.value[i].userId == key) {
      return `${judgeList.value[i].name}`;
    }
  }
};
const formatScore = (row, column, cellValue) => {
  return cellValue < 0 ? 0 : cellValue;
};
const Return = (item) => {
  SelectedForm.value.restartCheck.restartCheck = item;
  const params = {
    projectId: id.value,
    projectCode: projectInfo.value.oaCode,
    projectJudgeId: judgeId.value,
    signStr: item,
    type: "sign_end",
  };
  auditsign(params).then((res) => {
    if (res.code == "200") {
      getInfo();
    }
  });
};
const StartSingin = () => {
  Tablet.value.beginSign();
};
const prevPage = () => {
  if (Previous.value == "taskSkill") {
    emit("next-step", Previous.value);
  } else {
    ElMessage({
      message: "无法返回上一步",
      type: "error",
    });
  }
};
const Previous = ref("");
onMounted(() => {
  getInfo();
  queryTaskId({ projectId: id.value }).then((res) => {
    Previous.value = res.data;
  });
});
</script>

<style scoped lang="scss">
@use "./judge";
:deep(.end th) {
  border: 1px solid transparent;
  border-top: 1px solid #06c;
}
:deep(.el-table thead.is-group th.el-table__cell) {
  background-color: #fff;
}
</style>
